import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Modal, Drawer ,Table, Tag, Radio, Space} from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import { queryRule } from './service';
import {history} from "umi";
import request from "@/utils/request";

const TableList = () => {
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [delValue, setDelValue] = useState({});

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    request(`/api/miner/del?MinerId=${delValue.MinerId}`).then(res=>{
      if (res.Code != 0 ){
        message.error(res.Msg)
      }
    })
    setIsModalVisible(false);
    message.success('删除成功！');

    location.reload()
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };



  const columns = [
    {
      title: '矿工号',
      dataIndex: 'MinerId',
    },
    {
      title: '矿池名称',
      dataIndex: 'PoolName',
    },
    {
      title: '扇区大小',
      dataIndex: 'Size',
    },
    {
      title: 'WorkerKey',
      dataIndex: 'RoundWinnerWorkerKey',
      hideInForm: true,
      width:150,
      render: (text) => {
        let result = ""

          for (let i = 0; i < text.length; i++) {
            if (result != ""){
              result += ", "
            }
              result += text[i]

          }


        return result
      },
    },
     {
      title: '是否同步',
      dataIndex: 'IsSyncRoundWinner',
      render: (IsSyncRoundWinner) => {


         console.log(IsSyncRoundWinner)
          let color = 'green';
          let text = '不在同步'
          if (IsSyncRoundWinner === true) {
            color = 'volcano';
            text = '在同步'
          }
          return (
          <span>
            <Tag color={color}>
              {text}
            </Tag>
            </span>
          );


      }
    },{
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>
            <a
              onClick={()=>{
                request(`/api/miner/syncSingleMinerIdRoundWinner?MinerId=${record.MinerId}`).then(res=>{
                  if (res.Code != 0 ){
                    message.error(res.Msg)
                  }else{
                    message.success("成功开始同步"+record.MinerId+"矿工出块权")
                  }
                })
              }}
            >
              同步出块权
            </a>
            <Divider type="vertical" />
            <a onClick={()=>{
              history.push({
                pathname: '/minerAdd',
                query: {
                  minerId: record.MinerId,
                },
              })
            }}>更新</a>
            <Divider type="vertical" />
            <a
            onClick={()=>{
              setDelValue(record)
              showModal()
            }}
          >
            删除
          </a>
          </>
        )
      },
    },
  ];

  const request2 = async(
    // 第一个参数 params 查询表单和 params 参数的结合
    // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
    params ,
    sorter,
    filter,
  ) => {
    // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
    // 如果需要转化参数可以在这里进行修改
    console.log(params)

    const result = await queryRule({...params,sorter,filter});
    if (result.Code != 0) {
      message.error(result.Msg)
      return
    }
    console.log(result)
    return {
      data:result.Data.Data,
      success:result.Code === 0,
      total:result.Data.Total,
    };
  }


  return (

    <PageContainer>

      <ProTable
        headerTitle="矿工列表"
        actionRef={actionRef}
        rowKey="MinerId"
        search={false}
        options={false}
        toolBarRender={() => [
          <Button type="primary" onClick={() => history.push({
            pathname: '/minerAdd',
          })}>
            <PlusOutlined /> 新建
          </Button>,
          <Button onClick={()=>{
            request(`/api/miner/syncAllRoundWinner`).then(res=>{
              if (res.Code != 0 ){
                message.error(res.Msg)
              }else{
                message.success("成功开始同步所有矿工出块权")
              }
            })
          }} type="primary" >
            同步所有矿工出块权
          </Button>,

          <Button onClick={()=>{
            request(`/api/index/syncExpend`).then(res=>{
              if (res.Code != 0 ){
                message.error(res.Msg)
              }else{
                message.success("成功开始同步所有矿工支出监控")
              }
            })
          }} type="primary" >
            同步所有矿工支出监控
          </Button>,

          <Button onClick={()=>{
            request(`/api/index/SyncIncome`).then(res=>{
              if (res.Code != 0 ){
                message.error(res.Msg)
              }else{
                message.success("成功开始同步所有矿工收入监控")
              }
            })
          }} type="primary" >
            同步所有矿工收入监控
          </Button>,
        ]}
        request={request2}
        columns={columns}
      />
      <Modal title="删除矿工" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <p>是否确定删除{delValue.MinerId}矿工</p>
      </Modal>

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.name && (
          <ProDescriptions
            column={2}
            title={row?.name}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
